<template>
  <div class="todo">
    <input type="text" v-model="state.inpv" @keypress="add($event)">
    <div class="content">
       <div class="item" v-for="(item,index) in comditionList" :key="index" >
         <img v-if="item.complete" src="../assets/mark/checked.svg" alt="" @click="check(item)">
         <img v-else src="../assets/mark/uncheck.svg" alt="" @click="check(item)">
         <p :class="[item.complete?'complete':'']">{{item.value}}</p>
         <img class="close" src="../assets/mark/close.svg" alt="" @click="remove(item,index)">
       </div>
    </div>
    <div class="footer">
        <button @click="state.showType=1">所有</button>
        <button @click="state.showType=2">待办</button>
        <button @click="state.showType=3">已完成</button>
    </div>

  </div>
</template>

<script>
import { reactive, computed, watchEffect } from "vue";
// import { effect } from "@vue/reactivity";

const TODOKEY = "todo-data";

function userStorage(key, defvalue = []) {
  let data = reactive({});
  Object.assign(
    data,
    (localStorage[key] && JSON.parse(localStorage[key])) || defvalue
  );
  // effect(() => {
  //   localStorage[key] = JSON.stringify(data);
  // });
  watchEffect(() => {
    localStorage[key] = JSON.stringify(data);
  });

  return data;
}

export default {
  name: "TodoList",
  setup() {
    // let state = reactive({
    //   inpv: "",
    //   list: [{ value: "测试1", complete: 1 }, { value: "测2", complete: 1 }],
    //   showType: 1 //1： 所有  2：待办  3：已完成
    // });
    let state = userStorage(TODOKEY, {
      inpv: "",
      list: [],
      showType: 1 //1： 所有  2：待办  3：已完成
    });

    function add(e) {
      if (e.keyCode === 13 && state.inpv && state.inpv.length > 0) {
        state.list.push({
          value: state.inpv,
          complete: 0
        });
        state.inpv = "";
      }
    }

    function check(item) {
      item.complete = !item.complete;
    }

    function remove(item, index) {
      state.list.splice(index, 1);
    }

    let comditionList = computed(() => {
      if (state.showType == 2) {
        return state.list.filter(o => o.complete === 0);
      } else if (state.showType === 3) {
        return state.list.filter(o => o.complete === 1);
      } else {
        return state.list;
      }
    });

    return { state, comditionList, add, check, remove };
  }
};
</script>

<style  lang="scss" scoped>
.todo {
  width: 300px;
  margin: 10px;
  border: 1px gray solid;
  border-radius: 8px;
  input {
    height: 30px;
  }
  .content {
    .item {
      border-bottom: 1px gray solid;
      display: flex;
      img {
        margin: 0 8px;
        cursor: pointer;
      }
      p {
        flex-grow: 2;
        text-align: center;
      }
      p.complete {
        text-decoration: line-through;
        color: grey;
      }

      .close {
        margin-left: auto;
      }
    }
  }
  .footer {
    margin: 8px;
    display: flex;
    justify-items: flex-end;
  }
}
</style>
